/**
 * @FileName: CmmcFtpUtil.java
 * @Author
 * @Description:
 * @Date 2016年3月18日 下午2:42:40
 * @CopyRight ZTE Corporation
 */
package cn.hpclub.server.service.ds;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;

public class CmccFtpUtil{
    private static Logger logger     = Logger.getLogger(CmccFtpUtil.class);
    /* 中国移动FTP服务器的连接信息 */
    // IP地址
    private String        serverIp;
    // 端口号
    private int           serverPort = 21;
    // 用户名
    private String        username;
    // 密码
    private String        password;
    // 编码集
    private String        encoding   = "gb2312";

    private String        remotePath = "/";
    private FTPClient     ftpClient;

    /**
     * @Title: downloadOrgFile
     * @Description:下载CMCC FTP最新GroupMsg文件
     * @param destFilePath
     *            下载文件路径
     * @throws IOException
     *             void
     * @throws NoNewDataException
     */
    public String downloadFile(String destFilePath, String lastImportFile) throws IOException, NoNewDataException{
        ftpClient = loginFtp(serverIp, serverPort, username, password, encoding);
        FTPFile file = getSourceFile(ftpClient, remotePath);
        logger.debug("newestFile=" + file.toFormattedString());
        if(lastImportFile.equals(file.getName())){
            throw new NoNewDataException("无新数据.");
        }
        ftpClient.retrieveFile(file.getName(), new FileOutputStream(destFilePath));
        return file.getName();
    }

    public void uploadFile(String destFileName, InputStream inputSteam) throws IOException{
        logger.debug("uploadFile.destDirPath=" + remotePath + ",destFileName=" + destFileName);
        ftpClient = loginFtp(serverIp, serverPort, username, password, encoding);
        ftpClient.changeWorkingDirectory(remotePath);
        // 设置处理文件的类型为字节流的形式
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        // 如果缺省该句 传输txt正常 但图片和其他格式的文件传输出现乱码
        ftpClient.storeFile(destFileName, inputSteam);
    }

    public void closeConnection(){
        if(null != ftpClient && ftpClient.isConnected()){
            try{
                logger.debug("ftpClient has logout");
                ftpClient.logout();
            }
            catch(IOException e){
                e.printStackTrace();
            }
        }
    }

    /**
     * @Title: getSourceFile
     * @Description:从服务器/目录下获取最新文件
     * @param remotePath
     * @throws IOException
     *             FTPFile
     */
    private static FTPFile getSourceFile(FTPClient ftpClient, String remotePath) throws IOException{
        FTPFile[] ftpFiles = ftpClient.listFiles(remotePath);
        FTPFile newestFile = ftpFiles[0];
        for(int i = 1; i < ftpFiles.length; i++){
            FTPFile file = ftpFiles[i];
            if(file.isDirectory()){
                continue;
            }
            if(file.getTimestamp().after(newestFile.getTimestamp())){
                newestFile = file;
            }
        }
        return newestFile;
    }

    /**
     * 本方法用户登录远程的FTP服务器
     * 
     * @param url
     *            FTP的IP地址
     * @param port
     *            FTP服务器端口
     * @param userName
     *            登录FTP的用户名
     * @param password
     *            登录FTP的密码
     * @return FTPClient 返回为FTPClient对象
     * @throws IOException
     */
    private FTPClient loginFtp(String url, int port, String userName, String password, String endocing)
            throws IOException{
        FTPClient ftpClient = new FTPClient();
        logger.debug(" start to connect FTP server !");
        logger.debug("ip地址:   " + url);
        logger.debug("端口号:    " + port);
        logger.debug("用户名:    " + userName);
        logger.debug("密码:      " + password);

        // 配置端口
        ftpClient.setDefaultPort(port);
        // 配置编码集
        ftpClient.setControlEncoding(endocing);
        // 连接FTP服务器
        ftpClient.connect(url);
        ftpClient.enterLocalPassiveMode();
        // 登陆FTP服务器 URLEncoder.encode(password,"UTF-8")
        if(ftpClient.login(userName, password)){
            logger.debug(" login success !");
            if(FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){
                logger.debug(" connect success !");
                return ftpClient;
            }
        }
        throw new IOException("login FTP server error, please check it!");
    }

    public CmccFtpUtil(String serverIp, int serverPort, String username, String password, String encoding,
            String remotePath){
        this.serverIp = serverIp;
        this.serverPort = serverPort;
        this.username = username;
        this.password = password;
        this.encoding = encoding;
        this.remotePath = remotePath;
        logger.debug(toString());
    }

    /**
     * @return
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString(){
        return "CmccFtpUtil [serverIp=" + serverIp + ", serverPort=" + serverPort + ", username=" + username
                + ", password=" + password + ", encoding=" + encoding + ", remotePath=" + remotePath + "]";
    }

    public String getServerIp(){
        return serverIp;
    }

    public static class NoNewDataException extends Exception{
        private static final long serialVersionUID = -7199699560229583848L;

        public NoNewDataException(String msg){
            super(msg);
        }
    }

}
